package _5thread;

import java.util.concurrent.Semaphore;

/**
 * @description:
 * @author: wang zhen
 * @create: 2022-06-08 15:06
 */
public class SemaphoreTest {

    public static void main(String[] args) throws Exception{

        Semaphore semaphore=new Semaphore(3);

        Thread thread1=new Thread(){

            @Override
            public void run() {

                try {
                    if(semaphore.tryAcquire()){
                        System.out.println("1抢到了");

                    }else{
                        System.out.println("1没抢到");
                    }


                }finally {
                    //semaphore.release();
                }

            }
        };

        Thread thread2=new Thread(){

            @Override
            public void run() {
                try {
                    if(semaphore.tryAcquire()){
                        System.out.println("2抢到了");

                    }else{
                        System.out.println("2没抢到");
                    }

                }finally {
                    //semaphore.release();
                }
            }
        };

        Thread thread3=new Thread(){

            @Override
            public void run() {
                try {
                    if(semaphore.tryAcquire()){
                        System.out.println("3抢到了");

                    }else{
                        System.out.println("3没抢到");
                    }

                }finally {
                    //semaphore.release();
                }
            }
        };

        Thread thread4=new Thread(){

            @Override
            public void run() {
                try {
                    if(semaphore.tryAcquire()){
                        System.out.println("4抢到了");

                    }else{
                        System.out.println("4没抢到");
                    }

                }finally {
                    //semaphore.release();
                }
            }
        };

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
